package com.lw.leetcode.linked.b;

import com.lw.leetcode.linked.ListNode;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * 817. 链表组件
 *
 * @author liw
 * @version 1.0
 * @date 2021/7/21 10:35
 */
public class NumComponents {

    public int numComponents(ListNode head, int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>(nums.length << 1);
        for (int item : nums) {
            map.put(item, 1);
        }
        int res = 0;

        while (head != null) {
            if (map.get(head.val) != null) {
                while (head != null && map.get(head.val) != null) {
                    head = head.next;
                }
                res++;
            } else {
                head = head.next;
            }
        }
        return res;
    }

    public int numComponents2(ListNode head, int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int item : nums) {

            if (map.containsKey(item)) {
                map.put(item, map.get(item) + 1);
            } else {
                map.put(item, 1);
            }
        }
        int res = 0;
        while (head != null) {
            if (map.containsKey(head.val)) {
                while (head != null && map.containsKey(head.val)) {
                    head = head.next;
                }
                res++;
            } else {
                head = head.next;
            }

        }
        return res;
    }
}